var app = getApp()
const db = wx.cloud.database();
const command = db.command;
Page({
  data: {
    globalData:{
      StatusBar:'',
      Custom:'',
      CustomBar:'',
    },
    talkto:'',
    newsList:[],
    openid:'',
    animation:false,
    voice:false,
    sendout:false,
    camera:false,
    news:'',
    pression:[],
    emojis:false,
    curra:0,
    feature:[
      { src: 'cloud://wccloud-fm7zt.7763-wccloud-fm7zt-1301413717/icon/album.png', name: '相册' }
    ],
    alcur:false,
    vision:'',
    time:'',
    duration:'',
    playing:false,
    cuindex:'',
  },
  fanhui:function(e){
    wx.navigateBack({
      delta: 1
    })
  },

  cuinbut:function(e){
    let that = this
    setTimeout(function () {
      wx.createSelectorQuery().select('#chat-height').boundingClientRect(function (rect) {
        that.setData({
          chatheight: parseFloat(rect.height) + parseFloat(that.data.curra),
          curr: 'jump' + JSON.stringify(that.data.newsList.length - 1)
        })
      }).exec()
    }, 100)
  },

  onShow:function(e){
    this.setData({
      curr: 'jump' + JSON.stringify(this.data.newsList.length-1)
    })
  },

  onLoad: function (options) {
    // 当前师傅的true名字
    // console.log(options.userA);
    // 当前师傅聊天的用户的名字
    // console.log(options.userB);
    // 获取这两个人的聊天记录
    db.collection('chatroom').where(command.and([
      {
        userA:options.userB,
      },
      {
        userB:options.userA,
      }
    ])).get().then(res=>{
      // console.log(res.data[0].detail);
      var getcloud_message = res.data[0].detail;
      this.setData({
        newsList:getcloud_message,
      })
    })
    // 监听数据库数据变化并写入到data中
    const _this = this
    db.collection('chatroom').where(command.and([
      {
        userA:options.userB,
      },
      {
        userB:options.userA,
      }
    ])).watch({
      onChange: function (snapshot) {
        // console.log(snapshot.docs[0].detail);
        var latesetnews = snapshot.docs[0].detail
        _this.setData({
          newsList:latesetnews,
        })
        _this.cuinbut();
        console.log("消息发送成功");
      }, onError: function (err) {
        console.error('the watch closed because of error', err)
      },
      
    })


    let that = this
    wx.getSystemInfo({
      success: e => {
        that.data.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          that.data.globalData.Custom = capsule;
          that.data.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          that.data.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })
    that.setData({
      talkto:options.userB,
      openid:options.userA,
      globalData: that.data.globalData,
      // newsList: wx.getStorageSync('newsList'),
      pression: app.emoji.pression,
      vision: wx.getRecorderManager(),
    })
    this.cuinbut();
  },
  getkey:function(e){
    console.log(e);
    this.setData({
      curra: e.detail.height,
      emojis:false
    })
    this.cuinbut();
  },
  getblur:function(e){
    this.setData({
      curra: 0,
    })
    this.cuinbut();
  },
  onReady: function (e) {
    this.cuinbut();
  },
  moninput:function(e){
    let that = this
    that.cuinbut();
    this.setData({
      sendout: e.detail.value?true:false,
      news: e.detail.value,
    })
  },
  scrollstart:function(e){
    this.setData({
      emojis: false,
    })
  },
  speak:function(e){
    this.setData({
      voice: !this.data.voice,
      emojis:false,
      camera:false,
    })
    this.cuinbut();
  },
  emoji:function(e){
    this.setData({
      emojis: !this.data.emojis,
      voice:false,
      camera:false,
    })
    this.cuinbut();
  },
  camerax:function(e){
    this.setData({
      camera: !this.data.camera,
      voice: false,
      emojis: false,
    })
    this.cuinbut();
  },
  upload:function(e){
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        const src = res.tempFilePaths[0]
        wx.getImageInfo({
          src,
          success: function (res) {
            const { width, height } = res
            const newChatList = [...that.data.newsList,{
              news_type: 'image',
              news_centent: { src, width, height },
              openid: that.data.openid,
            }]
            that.setData({
              animation: true,
              newsList: newChatList,
            })
            wx.setStorageSync('newsList', newChatList);
            that.cuinbut();
          }
        })
      }
    })
  },
  picture:function(e){
    let src = e.currentTarget.dataset.src
    wx.previewImage({
      current: src,
      urls: [src]
    })
  },
  message:function(e){
    let that = this
    const newChatList = [...that.data.newsList, {
      news_type: 'text',
      news_centent: that.data.news,
      openid: that.data.openid,
    }]
    that.setData({
      animation: true,
      newsList: newChatList,
      sendout:false,
      news: '',
    })
    wx.setStorageSync('newsList', newChatList);
    var maxnum = newChatList.length;
    // console.log(newChatList[maxnum-1]);
    var latestnew = newChatList[maxnum-1]
    wx.cloud.callFunction({
      name:'update',
      data:{
        options:'send_message1',
        userA :this.data.openid,
        userB:this.data.talkto,
        detail:latestnew,
      }
    }).then(res=>{
      console.log("消息已同步到数据库");
    })
    that.cuinbut();
  },

  expression:function(e){
    let item = e.currentTarget.dataset.item
    this.setData({
      sendout: true,
      news: this.data.news+=item,
    })
  },

  featch:function(e){
    let that = this
    let index = e.currentTarget.dataset.index
    if(index == 0){
      that.upload();
    }
  },

  touchdown: function (e) {
    let that = this
    wx.stopVoice();
    that.setData({
      alcur: true,
      playing: false,
      cuindex: ''
    })
    that.data.duration = 0
    that.data.time = setInterval(function () {
      that.setData({
        duration: that.data.duration+1
      })
    },1000)
    wx.startRecord({
      success: function (res) {
        const newChatList = [...that.data.newsList, {
          news_type: 'voice',
          news_centent: { voice: res.tempFilePath, dimen: that.data.duration},
          openid: that.data.openid,
        }]
        that.setData({
          newsList: newChatList,
        })
        wx.setStorageSync('newsList', newChatList);
        that.cuinbut();
      },
      fail:function(e){
        that.touchup();
      }
    })
  },
  touchup: function (e) {
    let that = this
    wx.stopRecord()
    clearInterval(that.data.time)
    that.setData({
      alcur:false
    })
  },
  play: function (e) {
    let that = this
    let voice = e.currentTarget.dataset.voice
    var index = e.currentTarget.dataset.index
    if (!that.data.playing){
      that.setData({
        playing:true,
        cuindex:index
      })
      wx.playVoice({
        filePath: voice,
        success: function () {
          that.setData({
            playing: false,
            cuindex:''
          })
        },
      })
    }
  },
  suspend:function(e){
    wx.stopVoice();
    this.setData({
      playing: false,
      cuindex: ''
    })
  },
})
